<?php

namespace App\Http\Controllers\Api;

use Log;
use App\Models\User;
use App\Models\UserAuth;
use App\Models\Oauth;
use Hash;
use App\Http\Requests\UserRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Illuminate\Support\Facades\Redis;
// use Overtrue\Socialite\SocialiteManager;
// use App\Http\Resources\UserResource;
use Socialite;

class UserController extends Controller
{
    //用户注册
    public function signup($name, $phone, $avatar_url){
        $user = User::create([
            'name' => $name,
            'phone' => $phone,
            'avatar_url' => $avatar_url,
        ]);
        return $user;
    }

    // 登录，生成token
    public function createToken($identifier, $password, $type, $error) {
        $token = Auth::guard('api')->attempt(
            [
                'identifier' => $identifier,
                'identity_type' => $type,
                'password' => $password
            ]
        );

        if ($token) {
            $userAuth = Auth::guard('api')->user();
            $user = User::find($userAuth->user_id);
            $user->update([$user->updated_at = time()]);
            return $this->success(['token' => $token, 'is_activated' => $user->is_activated]);
        }
        return $this->failed($error, 200);
    }

    // 登录或注册
    public function login(Request $request){
        $phone   = $request->phone;
        $captcha = $request->captcha;
        $type    = $request->type;
        $password = $request->password;
        $data = [];
        $error = ($type === 'captcha') ? '登录失败！' : '密码错误！';

        // 短信登录
        if ($type === 'captcha') {
            $smsController = new SmsController();
            $check_result =  $smsController->check_captcha($phone, $captcha)->original;

            if ($check_result['status'] != 'success') {
                return $check_result;
            }

            // 没有就创建新用户
            $user = [
                'name' => $phone,
                'phone' => $phone,
            ];
            $userInfo = User::firstOrCreate(['phone' => $phone], $user);

            // 创建一条短信登录数据，存在就更新随机密码
            $smsIdentifier = [
                'user_id' => $userInfo->id,
                'identity_type' => 'oauth',
                'identifier' => $phone,
                'password' => bcrypt(str_random(16))
            ];
            UserAuth::updateOrCreate([
                'identity_type' => 'oauth',
                'identifier' => $phone
            ], $smsIdentifier);

            $password = $smsIdentifier['password'];
            $type = 'oauth';
        }
        
        return $this->createToken($phone, $password, $type, $error);
    }

    // 已经微信授权，绑定手机号
    public function bindPhone(Request $request) {
        $phone = $request->phone;
        $openid = $request->openid;
        $captcha = $request->captcha;

        $oauth = Oauth::where('oauth_id', $openid)->first();
        if ($oauth['user_id']) {
            return $this->failed('该微信号已绑定过手机号！', 200);
        }

        // 短信校验
        $smsController = new SmsController();
        $check_result =  $smsController->check_captcha($phone, $captcha)->original;

        if ($check_result['status'] != 'success') {
            return $check_result;
        }

        $oauth_info = json_decode($oauth->info);

        $userInfo = [
            'name' => $oauth_info->nickname,
            'avatar_url' => $oauth_info->headimgurl,
            'phone' => $phone,
        ];

        $user = User::updateOrCreate([ 'phone' => $phone ], $userInfo);
        $oauth->update(['user_id' => $user->id]);

        $wechatIdentifier = [
            'user_id' => $user->id,
            'identity_type' => 'oauth',
            'identifier' => $phone,
            'password' => bcrypt(str_random(16))
        ];
        UserAuth::updateOrCreate([
            'user_id' => $user->id,
            'identity_type' => 'oauth',
            'identifier' => $phone
        ], $wechatIdentifier);

        // return $this->success('绑定成功！');
        return $this->createToken($phone, $wechatIdentifier['password'], 'oauth', '登录失败！');
    }

    // 校验短信
    public function check_captcha(Request $request) {
        $phone = $request->phone;
        $captcha = $request->captcha;
        $smsController = new SmsController();
        $check_result =  $smsController->check_captcha($phone, $captcha)->original;

        if ($check_result['status'] != 'success') {
            return $check_result;
        }
        Redis::setex('password:'.$phone, 300, $captcha);
        return $this->success(['phone' => $phone, 'unSetPassword' => true]);
    }

    // 忘记密码或未设置密码
    public function setPassword(Request $request) {
        $password = $request->password;

        $userAuth = Auth::guard('api')->user();
        $user = User::find($userAuth->user_id);

        $phoneIdentifier = [
            'user_id' => $user->id,
            'identity_type' => 'password',
            'identifier' => $user->phone,
            'password' => $password
        ];
        UserAuth::updateOrCreate([
            'user_id' => $user->id,
            'identity_type' => 'password',
            'identifier' => $user->phone,
        ], $phoneIdentifier);

        return $this->success('密码设置成功！');
    }

    // 忘记密码，重置密码
    public function resetPassword(Request $request) {
        $password = $request->password;
        $phone = $request->phone;
        $captcha = $request->captcha;

        $redisCode = Redis::get('password:'.$phone);
        
        if ($captcha != $redisCode) {
            return $this->failed('密码设置失败，请重新获取验证码！', 200);
        }
        $user = User::where('phone', $phone)->first();
        $phoneIdentifier = [
            'user_id' => $user->id,
            'identity_type' => 'password',
            'identifier' => $phone,
            'password' => $password
        ];
        UserAuth::updateOrCreate([
            'user_id' => $user->id,
            'identity_type' => 'password',
            'identifier' => $user->phone,
        ], $phoneIdentifier);

        return $this->success('密码重置成功！');
    }

    // 修改密码
    // public function resetPassword(UserRequest $request){
    //     $userAuth = Auth::guard('api')->user();
    //     $oldpassword = $request->old_password;

    //     $curUserAuth
    //     if (!Hash::check($oldpassword, $user->password)) {
    //         return $this->failed('旧密码错误', 200);
    //     }

    //     // 修改所有关联账号密码
    //     $userAuth = UserAuth::where(['user_id', $user->user_id, 'identity_type' => 'password'])->first();
    //     // foreach($userAuths as $item){
    //     //     $item->update(['password' => $request->new_password]);
    //     // }
    //     $userAuth->update(['password' => $request->new_password]);

    //     return $this->message('密码修改成功');
    // }

    // 返回当前登录用户信息
    public function info(){
        $userAuth = Auth::guard('api')->user();
        $user = User::find($userAuth->user_id);

        $oauth = Oauth::where('user_id', $userAuth->user_id)->first();
        if ($oauth) {
            $user->oauth_id = $oauth->oauth_id;
        }

        // 是否管理员
        if ($user->is_admin == 1)
            $user->admin = true;
        return $this->success($user);
    }

    // 用户退出
    public function logout(){
        Auth::guard('api')->logout();
        return $this->message('退出登录成功!');
    }

    //返回指定用户信息
    public function show(UserRequest $request){
        $user = User::find($request->id);
        return $this->success($user);
    }

    //返回用户列表 10个用户为一页
    public function list(){
        $users = User::orderBy('created_at', 'desc')->paginate(10);
        foreach($users as $item) {
            $oauth = Oauth::where('user_id', $item->id)->first();
            if ($oauth) {
                $item->oauth_id = $oauth->oauth_id;
            }
            if ($item->is_admin) {
                $item->admin = true;
            }
        }
        return $this->success($users);
    }


    // 筛选列表
    public function search(Request $request) {
        $id = $request->id;
        $phone = $request->phone;
        if ($id) {
            $user = User::where('id', $id)->get();
        }
        if ($phone) {
            $user = User::where('phone', $phone)->get();
        }
        return $this->success($user);  
    }

    // 设置管理员权限
    public function setAdmin(Request $request) {
        $id = $request->id;
        $phone = $request->phone;
        $user = '';
        if ($id) {
            $user = User::findOrFail($id);
        }
        if ($phone) {
            $user = User::where('phone', $phone)->first();
        }
        if (!$user) return $this->failed('用户不存在', 200);
        $user->is_admin = 1;
        $user->save();
        return $this->message('已设置成管理员！');
    }

    // 取消管理员权限
    public function cancelAdmin(Request $request) {
        $id = $request->id;
        $phone = $request->phone;
        $user = '';
        if ($id) {
            $user = User::findOrFail($id);
        }
        if ($phone) {
            $user = User::where('phone', $phone)->first();
        }
        if (!$user) return $this->failed('用户不存在', 200);
        $user->is_admin = null;
        $user->save();
        return $this->message('已取消管理员权限！');
    }

    // 管理员列表
    public function AdminList(Request $request) {
        $admins = User::where('is_admin', 1)->paginate(10);
        return $this->success($admins);
    }

}
